//
//  PrinterListTableViewController.m
//  ZNHXManagement
//
//  Created by 四川中农 on 2018/10/26.
//  Copyright © 2018年 四川中农. All rights reserved.
//

#import "PrinterListTableViewController.h"
#import "PrinterTableViewCell.h"
#import "printerlibs_caysnpos_en.h"
#import "PrinterModel.h"
#import "BleManager.h"

@interface PrinterListTableViewController ()
@property (nonatomic, strong) NSMutableArray *dataArray;
@property void *pHandle;
@end

@implementation PrinterListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_return"] style:UIBarButtonItemStylePlain target:self action:@selector(backMethod)];
    self.navigationItem.leftBarButtonItem = item;
    
    self.title = @"打印机列表";
    [self getPrinterList];
    self.tableView.tableFooterView = [UIView new];
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray  array];
    }
    return _dataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PrinterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PrinterTableViewCell" forIndexPath:indexPath];
    PrinterModel *model = self.dataArray[indexPath.row];
    cell.deviceLabel.text = [NSString stringWithFormat:@"%@:%@",model.name,model.address];
    cell.selecImage.highlighted = NO;
    if ([model.name isEqualToString:[BleManager share].name]) {
        cell.selecImage.highlighted = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        PrinterModel *model = self.dataArray[indexPath.row];
        self.pHandle = CaysnPos_OpenBT4ByConnectA([model.address UTF8String]);
        if (self.pHandle)
            CaysnPos_SetBT4WriteMode(self.pHandle, true, 120, 3600 * 1000, 3);
        
        if (self.pHandle) {
            CaysnPos_SetClosedEvent(self.pHandle, closed_event, (__bridge void *)self);
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            [BleManager share].name = model.name;
            if (self.pHandle != NULL) {
                [BleManager share].pHandle = self.pHandle;
            }
//            if ([self.delegate respondsToSelector:@selector(backDeviceName:)]) {
//                [self.delegate backDeviceName:model.name];
//            }
            [self.navigationController popViewControllerAnimated:YES];
        });
    });
}

void closed_event(void *private_data)
{
    NSLog(@"closed_event");
    
}


- (void)getPrinterList{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        int cancel = 0;
        CaysnPos_EnumBleDeviceA(12000, &cancel, btdevice_discovered, (__bridge const void *)self);
        
    });
}

void btdevice_discovered(const char *device_name, const char *device_address, const void *private_data)
{
    if (device_name == nil) {
        return;
    }
    NSLog(@"BlePrinterDiscovered %s %s", device_name, device_address);
    dispatch_sync(dispatch_get_main_queue(), ^{
        PrinterListTableViewController *vc = (__bridge PrinterListTableViewController *)private_data;
        if (![vc.dataArray containsObject:[NSString stringWithFormat:@"%s",device_name]]) {
            __block BOOL isContains = NO;
            [vc.dataArray enumerateObjectsUsingBlock:^(PrinterModel * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.name isEqualToString:[NSString stringWithFormat:@"%s",device_name]]) {
                    *stop = YES;
                    isContains = YES;
                }
            }];
            if (isContains) {
                return;
            }
            PrinterModel *model = [[PrinterModel alloc] init];
            model.name = [NSString stringWithFormat:@"%s",device_name];
            model.address = [NSString stringWithFormat:@"%s",device_address];
            [vc.dataArray addObject:model];
            [vc.tableView reloadData];
        }
    });
}

@end
